<template>
  <div class="rule-sql-container">
    <div class="header">
      <h3>规则SQL语句展示</h3>
      <p class="data-count">共 {{ sqlData.length }} 组SQL数据</p>
    </div>

    <!-- 如果没有数据 -->
    <div
      v-if="!sqlData || sqlData.length === 0"
      class="no-data"
    >
      <el-empty description="暂无SQL数据">
        <el-icon><DocumentCopy /></el-icon>
      </el-empty>
    </div>

    <!-- SQL数据展示区域 -->
    <div v-else class="data-container">
      <div
        v-for="(item, index) in sqlData"
        :key="index"
        class="sql-item"
      >
        <!-- 标题：path -->
        <div class="item-header sticky-header">
          <div class="header-left">
            <el-tag type="primary" size="large" class="key-tag">
              {{ item.path }}
            </el-tag>
            <el-divider direction="vertical" />
            <span class="sql-count">
              SQL语句: {{ (item.sqlList || []).length }} 条
            </span>
          </div>
          <div class="header-actions">
            <el-button
              type="text"
              size="small"
              @click="toggleExpand(index)"
              class="expand-btn"
            >
              <el-icon v-if="!expanded[index]"><ArrowDown /></el-icon>
              <el-icon v-else><ArrowUp /></el-icon>
              {{ expanded[index] ? '收起' : '展开' }}
            </el-button>
            <el-divider direction="vertical" />
            <el-button
              type="text"
              size="small"
              @click="copySqlContent(item)"
              :loading="copyLoading[index]"
              class="copy-btn"
            >
              <el-icon><CopyDocument /></el-icon>
              复制全部
            </el-button>
          </div>
        </div>

        <!-- SQL内容展示框 -->
        <div class="sql-content-container">
          <div 
            class="sql-content" 
            :id="`sql-content-${index}`"
            :class="{ 'expanded': expanded[index] }"
          >
            <pre class="sql-text">{{ formatSqlContent(item.sqlList) }}</pre>
          </div>
          <div class="content-actions">
            <el-button
              type="primary"
              size="small"
              @click="copySqlContent(item, index)"
              :loading="copyLoading[index]"
            >
              <el-icon><CopyDocument /></el-icon>
              复制内容
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="toggleExpand(index)"
            >
              <el-icon v-if="!expanded[index]"><ArrowDown /></el-icon>
              <el-icon v-else><ArrowUp /></el-icon>
              {{ expanded[index] ? '收起' : '展开' }}
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 复制成功提示 -->
    <el-message
      v-if="showCopySuccess"
      type="success"
      :duration="2000"
      @close="showCopySuccess = false"
    >
      SQL内容已复制到剪贴板
    </el-message>
  </div>
</template>

<script setup>
/* eslint-env es6 */
/* global defineProps */
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { 
  DocumentCopy, 
  CopyDocument, 
  ArrowDown, 
  ArrowUp 
} from '@element-plus/icons-vue'

// 定义props
const props = defineProps({
  sqlData: {
    type: Array,
    default: () => [],
    validator: (value) => {
      // 验证数组中的每个元素都有path、sqlList字段
      return value.every(
        (item) =>
          typeof item === 'object' &&
          'path' in item &&
          'sqlList' in item
      )
    }
  }
})

// 响应式数据
const copyLoading = reactive({})
const expanded = reactive({})
const showCopySuccess = ref(false)

// 格式化SQL内容
const formatSqlContent = (sqlList) => {
  if (!sqlList || !Array.isArray(sqlList) || sqlList.length === 0) {
    return '-- 暂无SQL语句 --'
  }
  
  // 将多个SQL用分割线连接
  return sqlList
    .filter(sql => sql && sql.trim()) // 过滤空SQL
    .join('\n---------------------------------\n')
}

// 复制SQL内容
const copySqlContent = async (item, index) => {
  const content = formatSqlContent(item.sqlList)
  
  if (!content || content.trim() === '-- 暂无SQL语句 --') {
    ElMessage.warning('没有可复制的SQL内容')
    return
  }
  
  // 设置加载状态
  if (index !== undefined) {
    copyLoading[index] = true
  }
  
  try {
    // 使用现代剪贴板API
    if (navigator.clipboard && window.isSecureContext) {
      await navigator.clipboard.writeText(content)
    } else {
      // 降级方案：使用传统方法
      const textArea = document.createElement('textarea')
      textArea.value = content
      textArea.style.position = 'fixed'
      textArea.style.left = '-999999px'
      textArea.style.top = '-999999px'
      document.body.appendChild(textArea)
      textArea.focus()
      textArea.select()
      document.execCommand('copy')
      textArea.remove()
    }
    
    ElMessage.success({
      message: `已复制 ${item.path} 的SQL内容`,
      duration: 2000
    })
    
  } catch (error) {
    console.error('复制失败:', error)
    ElMessage.error('复制失败，请手动选择复制')
  } finally {
    // 清除加载状态
    if (index !== undefined) {
      copyLoading[index] = false
    }
  }
}

// 切换展开/收起状态
const toggleExpand = (index) => {
  expanded[index] = !expanded[index]
}

// 初始化展开状态
const initExpandStates = () => {
  props.sqlData.forEach((_, index) => {
    expanded[index] = false
    copyLoading[index] = false
  })
}

// 监听数据变化，重新初始化状态
watch(
  () => props.sqlData,
  () => {
    initExpandStates()
  },
  { immediate: true }
)
</script>

<style scoped>
.rule-sql-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-top: 20px;
  position: relative; /* 为sticky提供定位上下文 */
}

.header {
  margin-bottom: 20px;
  padding: 15px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header h3 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 20px;
  font-weight: 600;
}

.data-count {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.no-data {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.data-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
  position: relative; /* 确保sticky的定位上下文正确 */
}

.sql-item {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: visible; /* 改为visible确保sticky能正常工作 */
  margin-bottom: 20px;
  position: relative;
}

.item-header {
  padding: 10px 15px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 10px;
  min-height: 40px;
}

.sticky-header {
  position: sticky;
  top: 10px; /* 调整为更接近顶部的位置 */
  z-index: 100;
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
  flex: 1;
}

.key-tag {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  font-weight: 600;
  font-size: 12px;
  padding: 4px 8px;
}

.sql-count {
  font-size: 12px;
  opacity: 0.9;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 6px;
}

.expand-btn,
.copy-btn {
  color: white !important;
  border-color: rgba(255, 255, 255, 0.3);
  transition: all 0.2s ease;
  padding: 4px 8px;
  font-size: 12px;
  height: 28px;
}

.expand-btn:hover,
.copy-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.copy-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.sql-content-container {
  position: relative;
  overflow: visible; /* 确保不会影响sticky */
}

.sql-content {
  max-height: 300px;
  overflow-y: auto;
  background-color: #2d3748;
  border-radius: 0;
  transition: all 0.3s ease;
  position: relative; /* 确保不影响父级的sticky */
}

.sql-content.expanded {
  max-height: none !important;
  height: auto !important;
  overflow-y: visible; /* 展开时不需要滚动 */
}

.sql-text {
  margin: 0;
  padding: 20px;
  font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.5;
  color: #e2e8f0;
  background: transparent;
  white-space: pre-wrap;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

.content-actions {
  padding: 10px 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #e9ecef;
  display: flex;
  gap: 10px;
  justify-content: flex-end;
}

/* 滚动条样式 */
.sql-content::-webkit-scrollbar {
  width: 8px;
}

.sql-content::-webkit-scrollbar-track {
  background: #4a5568;
}

.sql-content::-webkit-scrollbar-thumb {
  background: #718096;
  border-radius: 4px;
}

.sql-content::-webkit-scrollbar-thumb:hover {
  background: #a0aec0;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .rule-sql-container {
    padding: 10px;
  }
  
  .item-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 8px 12px;
    min-height: auto;
  }
  
  .sticky-header {
    top: 5px; /* 移动端调整top值 */
  }
  
  .header-left {
    width: 100%;
    justify-content: space-between;
  }
  
  .header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .content-actions {
    flex-direction: column;
  }
  
  .sql-text {
    font-size: 12px;
    padding: 15px;
  }
}

/* 分割线样式 */
:deep(.el-divider--vertical) {
  margin: 0 8px;
  background-color: rgba(255, 255, 255, 0.3);
}
</style>